# coding:utf-8
from flask import request, current_app, render_template

from app.forms import NotChoices
from . import auth_bp
from .models import PublishDemandLog, AdminUser
from .log_forms import PublishDemandLogForm


@auth_bp.route('/publish_demand_logs', methods=['GET', 'POST'])
def publish_demand_logs():
    form = PublishDemandLogForm(formdata=request.form or request.args)

    admin_users = AdminUser.get_list_by_args(is_administrator=True)

    form.admin_id.choices = NotChoices + [(x.id, x.nickname) for x in admin_users]

    url_kwargs = {}
    query = PublishDemandLog.query
    if form.validate():

        query_kwargs, url_kwargs = form.generate_kwargs()

        # 根据 form 表单的值，构造Demand的query对象
        query = PublishDemandLog.generate_list_query_condition(
            args=query_kwargs,
            query=query
        )

    page = request.args.get('page', 1, type=int)
    pagination = query.paginate(
        page,
        per_page=current_app.config['FLASKY_COMMENTS_PER_PAGE'],
        error_out=False
    )
    data = pagination.items
    return render_template(
        'publish_demand_logs.html',
        data=data,
        pagination=pagination,
        page=page,
        form=form,
        url_kwargs=url_kwargs
    )
